<template>
  <el-main v-loading="open" element-loading-background="rgba(243,244,247,1)">
    <el-card>
      <el-input
        placeholder="请输入搜索内容"
        prefix-icon="el-icon-search"
        v-model="pageInfo.qurey"
        :clearable="true"
        style="width: 400px"
        @clear="getDishesList"
      >
        <el-button slot="append" icon="el-icon-search" @click="getDishesList()"></el-button>
      </el-input>
      <div class="right">
        <div class="right-info">
          <div class="right-operation">
            <el-button type="text" class="delete" @click="deleteList">批量删除</el-button>
            <span class="line">|</span>
            <el-button type="text" class="onSale" @click="saleStatus(true)">批量启售</el-button>
            <span class="line">|</span>
            <el-button type="text" class="stopSale" @click="saleStatus(false)">批量停售</el-button>
          </div>
          <div class="right-button">
            <el-button type="primary" @click="addDish">新建菜品</el-button>
          </div>
        </div>
      </div>
      <el-table
        @selection-change="change"
        :data="tableData"
        stripe
        style="width: 100%"
        border
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column prop="dishName" label="菜品名称" width="150"></el-table-column>
        <el-table-column label="图片" width="130">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="scope.row.dishImage" fit="cover">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="所属分类" width="100"></el-table-column>
        <el-table-column prop="shopName" label="所属商家" width="180"></el-table-column>
        <el-table-column label="售价" width="150">
          <template slot-scope="scope">
            <span>￥{{ scope.row.dishPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.dishStatus" @change="editStatus(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="dishText" label="简介" width="237"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" class="edit" @click="editDiolog(scope.row.id)">修改</el-button>
            <span class="line">|</span>
            <el-button type="text" class="delete" @click="deleteDiolog(scope.row.id, scope.row.dishImage)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="table">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageInfo.pageNum"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="pageInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <!-- 修改菜品信息的弹窗区域 -->
      <el-dialog title="修改菜品信息" :visible.sync="editDishDiolog" width="35%" @close="editDishDiologClose">
        <el-form ref="editDishRef" :model="editDishForm" label-width="80px" :rules="editDishRules">
          <el-form-item label="菜品名称" prop="dishName">
            <el-input v-model="editDishForm.dishName" clearable></el-input>
          </el-form-item>
          <el-form-item label="所属分类" prop="categoryName">
            <el-input v-model="editDishForm.categoryName" clearable></el-input>
          </el-form-item>
          <el-form-item label="售价" prop="dishPrice">
            <el-input v-model="editDishForm.dishPrice" clearable placeholder="请输入菜品价格"></el-input>
          </el-form-item>
          <el-form-item label="规格配置">
            <el-button type="primary" @click="addFlavore" v-if="dishFlavore.length == 0">添加口味</el-button>
            <div class="flavore" v-if="dishFlavore.length != 0">
              <div class="count" v-for="(item, index) in dishFlavore" :key="index">
                <el-select
                  clearable
                  v-model="item.name"
                  placeholder="请设置口味"
                  style="width: 150px; margin-bottom: 10px"
                  @change="changeFlavore(index, item.name)"
                  @clear="delArray(index)"
                >
                  <el-option v-for="(it, int) in flavors" :key="int" :label="it.name" :value="it.name"></el-option>
                </el-select>
                <div class="labal">
                  <el-tag
                    disable-transitions
                    v-for="(its, ints) in item.value"
                    :key="ints"
                    closable
                    style="margin-right: 10px; margin-bottom: 10px"
                    @close="delLabel(ints, index)"
                    >{{ its }}</el-tag
                  >
                </div>
              </div>
              <div class="fotter">
                <el-button type="primary" @click="addFlavore">添加口味</el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="菜品图片" prop="dishImage">
            <template>
              <el-upload
                class="upload-demo"
                action="http://localhost:8080/school/image/upload"
                :on-success="uploadSuccess"
                :on-remove="deleteImage"
                :on-progress="changeImage"
                :before-upload="beforeUpload"
                style="width: 300px"
                list-type="picture"
                :show-file-list="false"
              >
                <el-button size="small" type="primary">更换图片</el-button>
              </el-upload>
              <el-image style="width: 100px; height: 100px" :src="editDishForm.dishImage" fit="cover">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </template>
          </el-form-item>
          <el-form-item label="菜品简介" prop="dishText">
            <el-input v-model="editDishForm.dishText" clearable placeholder="请输入菜品简介" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDishDiolog = false">取 消</el-button>
          <el-button type="primary" @click="editSummit">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </el-main>
</template>

<script>
import QueryString from 'qs';
export default {
  name: 'Meals',
  data() {
    return {
      open: true,
      flavors: [],
      dishFlavore: [],
      checkStatus: [],
      checkBox: [],
      tableData: [],
      total: 0,
      pageInfo: {
        //模糊查询的数据
        qurey: '',
        //当前页数
        pageNum: 1,
        //每页显示的数据条数
        pageSize: 5,
      },
      //控制修改菜品信息弹窗的属性
      editDishDiolog: false,
      //修改菜品信息绑定的表单信息
      editDishForm: {},
      info: [],
      //修改菜品信息的验证规则
      editDishRules: {
        dishName: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
        categoryName: [{ required: true, message: '请选择菜品分类', trigger: 'blur' }],
        dishText: [{ required: true, message: '请选择菜品简介', trigger: 'blur' }],
        dishPrice: [{ required: true, message: '菜品价格不能为空', trigger: 'blur' }],
      },
    };
  },
  mounted() {
    this.info = JSON.parse(localStorage.getItem('userinfo'));
  },
  created() {
    this.openFullScreen();
    this.getDishesList();
    this.getFlavors();
  },

  methods: {
    beforeUpload(file) {
      console.log(file);
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1);

      const whiteList = ['jpg', 'png'];

      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message.error('上传文件只能是 jpg、png 格式');
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 3;

      if (!isLt2M) {
        return this.$message.error('上传文件大小不能超过 3MB，请选择其他图片');
      }
    },
    openFullScreen() {
      this.open = true;
      setTimeout(() => {
        this.open = false;
      }, 1000);
    },
    //获取菜品列表
    async getDishesList() {
      const { data: res } = await this.$http.get('dish/getDishList', {
        params: this.pageInfo,
      });
      if (res.code == 1) {
        this.tableData = res.data.records;
        for (let i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].dishStatus == 1) {
            this.tableData[i].dishStatus = true;
          }
          if (this.tableData[i].dishStatus == 0) {
            this.tableData[i].dishStatus = false;
          }
        }
        this.total = res.data.total;
      } else {
        this.$message.error('请求失败');
      }
    },
    handleSizeChange(newSize) {
      this.pageInfo.pageSize = newSize;
      this.getDishesList();
    },

    handleCurrentChange(newPageNum) {
      this.pageInfo.pageNum = newPageNum;
      this.getDishesList();
    },
    //添加菜品跳转页面
    addDish() {
      this.$router.push('/addDish');
    },
    //弹出修改对话框
    async editDiolog(id) {
      this.editDishDiolog = true;
      const { data: res } = await this.$http.get('dish/getById/' + id);
      if (res.code == 1) {
        this.editDishForm = res.data;
        this.dishFlavore = this.editDishForm.dishFlavore;
        console.log(this.editDishForm);
        for (let i = 0; i < this.dishFlavore.length; i++) {
          this.dishFlavore[i].value = JSON.parse(this.dishFlavore[i].value);
        }
        return;
      } else {
        return this.$message.error('数据获取失败');
      }
    },
    //监听修改对话框的关闭
    editDishDiologClose() {
      this.$refs.editDishRef.resetFields();
      this.dishFlavore = this.editDishForm.dishFlavore;
    },
    //更换图片时先进行该方法删除原有图片
    async changeImage() {
      const { data: res } = await this.$http.delete('image/deleteImage/' + this.editDishForm.dishImage);
      if (res.code == 1) {
        return this.$message.success('照片更换成功');
      } else {
        return this.$message.error('照片更换失败');
      }
    },
    //接受上传成功的返回的图片名称
    uploadSuccess(reponse) {
      this.editDishForm.dishImage = reponse.data;
    },
    //取消上传后删除图片
    async deleteImage() {
      const { data: res } = await this.$http.delete('image/deleteImage/' + this.editDishForm.dishImage);
      if (res.code == 1) {
        return this.$message.success(res.data);
      } else {
        return this.$message.error(res.msg);
      }
    },
    //点击确定更改菜品信息
    editSummit() {
      this.editDishDiolog = false;
      this.$refs.editDishRef.validate(async (valid) => {
        if (valid) {
          this.editDishForm.dishStatus = true ? '1' : '0';

          this.editDishForm.userName = this.info.userName;
          for (let i = 0; i < this.dishFlavore.length; i++) {
            this.dishFlavore[i].value = JSON.stringify(this.dishFlavore[i].value);
          }
          this.editDishForm.dishFlavore = this.dishFlavore;
          this.dishFlavore = [];
          const { data: res } = await this.$http.put('dish/updateDish', this.editDishForm);
          if (res.code == 1) {
            this.getDishesList();
            return this.$message.success(res.data);
          } else {
            return this.$message.error('菜品信息修改失败');
          }
        } else {
          return this.$message.error('表单校验失败');
        }
      });
    },
    //删除菜品信息
    async deleteDiolog(id, dishImage) {
      console.log(id);
      console.log(dishImage);
      const result = await this.$confirm('此操作将永久删除该菜品信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
        });
      });
      if (result == 'confirm') {
        if (dishImage == '') {
          const { data: res } = await this.$http.delete('dish/' + id);
          if (res.code == 1) {
            if (this.pageInfo.pageNum > (this.total - 1) / this.pageInfo.pageSize && (this.total - 1) % this.pageInfo.pageSize == 0) {
              this.pageInfo.pageNum = this.pageInfo.pageNum - 1;
            }
            this.getDishesList();
            return this.$message(res.data);
          }
        } else {
          const { data: res } = await this.$http.delete('dish/' + id);
          const { data: res2 } = await this.$http.delete('image/deleteImage/' + dishImage);
          if (res.code == 1 && res2.code == 1) {
            if (this.pageInfo.pageNum > (this.total - 1) / this.pageInfo.pageSize && (this.total - 1) % this.pageInfo.pageSize == 0) {
              this.pageInfo.pageNum = this.pageInfo.pageNum - 1;
            }
            this.getDishesList();
            return this.$message(res.data);
          }
        }
      } else {
        return this.$message.error('菜品信息删除失败');
      }
    },
    //监听用户状态的改变并向后台请求保存用户最新信息
    async editStatus(dishInfo) {
      if (dishInfo.dishStatus) {
        dishInfo.dishStatus = 1;
      } else {
        dishInfo.dishStatus = 0;
      }

      dishInfo.userName = this.info.userName;
      const { data: res } = await this.$http.put('dish/updateDish', dishInfo);
      if (res.code == 1) {
        this.getDishesList();
        return this.$message.success(res.data);
      } else {
        return this.$message.error('菜品状态修改失败');
      }
    },
    //监听多选框的改变
    change(val) {
      let checkArr = [];
      val.forEach((n) => {
        checkArr.push(n.id);
      });
      this.checkBox = checkArr;
      this.checkStatus = val;
    },
    //批量删除功能
    async deleteList() {
      const result = await this.$confirm('此操作将永久删除这些菜品信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
        });
      });
      if (result == 'confirm') {
        const date = QueryString.stringify({ ids: this.checkBox }, { arrayFormat: 'comma' });
        const { data: res } = await this.$http.delete('dish/deleteList', {
          params: this.$qs.parse(date),
        });
        if (res.code == 1) {
          this.getDishesList();
          return this.$message.success(res.data);
        } else {
          return this.$message.error('批量删除失败');
        }
      }
    },
    //批量启售与停售
    async saleStatus(status) {
      if (status == true) {
        for (let i = 0; i < this.checkStatus.length; i++) {
          this.checkStatus[i].dishStatus = 1;
          this.checkStatus[i].userName = this.info.userName;
        }
        const { data: res } = await this.$http.put('dish/updateList', this.checkStatus);
        if (res.code == 1) {
          this.getDishesList();
          return this.$message.success(res.data);
        } else {
          return this.$message.error('菜品批量启售失败');
        }
      }
      if (status == false) {
        for (let i = 0; i < this.checkStatus.length; i++) {
          this.checkStatus[i].dishStatus = 0;
          this.checkStatus[i].userName = this.info.userName;
        }
        const { data: res } = await this.$http.put('dish/updateList', this.checkStatus);
        if (res.code == 1) {
          this.getDishesList();
          return this.$message.success(res.data);
        } else {
          return this.$message.error('菜品批量停售失败');
        }
      }
    },
    changeFlavore(index, name) {
      for (let j = 0; j < this.dishFlavore.length - 1; j++) {
        if (this.dishFlavore[j].name === name) {
          this.delArray(index);
          this.$message.error('该口味信息已存在请重新输入');
        }
      }
      for (let i = 0; i < this.flavors.length; i++) {
        if (this.flavors[i].name == name) {
          this.dishFlavore[index].value = this.flavors[i].value;
        }
      }
    },
    delArray(index) {
      this.dishFlavore.splice(index, 1);
    },
    delLabel(ints, index) {
      this.dishFlavore[index].value.splice(ints, 1);
    },
    addFlavore() {
      this.dishFlavore.push({ name: '', value: [] });
    },
    getFlavors() {
      this.flavors = [
        { name: '甜味', value: ['无糖', '少糖', '半糖', '多糖', '全糖'] },
        { name: '温度', value: ['热饮', '常温', '去冰', '少冰', '多冰'] },
        { name: '忌口', value: ['不要葱', '不要蒜', '不要香菜', '不要辣'] },
        { name: '辣度', value: ['不辣', '微辣', '中辣', '重辣'] },
      ];
    },
  },
};
</script>

<style lang="scss" scoped>
.image-slot {
  .el-icon-picture-outline {
    font-size: 55px;
    line-height: 100px;
    text-align: center;
  }
}
.el-card {
  position: relative;
}
.right {
  display: inline-block;

  .right-info {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    position: absolute;
    right: 20px;
    top: 20px;
    .right-operation {
      margin-right: 30px;
    }
  }
}
.delete,
.stopSale {
  color: #f56c6c;
  font-size: 13px;
}
.line {
  color: #ebeef5;
  font-size: 13px;
  margin: 0 5px 0 5px;
}
.onSale {
  color: #419eff;
  font-size: 13px;
}
.edit {
  color: #ffc200;
  font-size: 13px;
}
.img {
  height: 70px;
  width: 80px;
}
.el-table {
  margin-top: 20px;
}
.table {
  display: flex;
  justify-content: space-evenly;
  margin-top: 25px;
}
.el-main {
  padding: 0px;
}
</style>